<template>
    <div class="dropdown" ref="dropdownRef">
        <a href="#" class="btn btn-outline-light my-2 dropdown-toggle" @click.prevent="toggleOpen">{{title}}</a>
        <ul class="dropdown-menu" :style="{display: 'block'}" v-if="isOpen">
            <slot></slot>
        </ul>
    </div>
</template>

<script lang="ts">
import { defineComponent,ref,onMounted,onUnmounted,watch } from 'vue'
import useClickOutside from '../hooks/useClickOutside'
export default defineComponent({
    name:'Dropdown',
    props:{
        title:{
            type: String,
            required: true
        }
    },
    setup () {
        const isOpen = ref(false)
        const dropdownRef = ref<null | HTMLElement>(null)
        const toggleOpen = () => {
            isOpen.value = !isOpen.value
        }

        // const handler = (e: MouseEvent) => {
        //     // 拿到节点 dropdownRef.value
        //     if(dropdownRef.value){
        //         // 是否包含下一个节点
        //         if(!dropdownRef.value.contains(e.target as HTMLElement) && isOpen.value){
        //             isOpen.value =false
        //         }
        //     }
        // }
        // onMounted(() => {
        //     document.addEventListener('click',handler)
        // })
        // onUnmounted(() => {
        //     document.removeEventListener('click',handler)
        // })

        const isClickOutside = useClickOutside(dropdownRef)
        
        watch(isClickOutside,()=>{
            if(isOpen.value && isClickOutside.value){
                isOpen.value = false
            }
        })  
        return {
            isOpen,
            toggleOpen,
            dropdownRef
        }
    }
})
</script>

<style scoped>

</style>
